import customtkinter as ctk
import threading
from tkinter import messagebox


class ConfigTab(ctk.CTkFrame):
    def __init__(self, parent, env: dict):
        super().__init__(parent)
        self._env = env
        self.on_save = None
        self.on_connect = None
        # 自动获取Cookie相关变量
        self._cookie_fetcher = None  # 浏览器Cookie获取器实例
        self._countdown_value = 0  # 倒计时当前值
        self._countdown_after_id = None  # 倒计时定时器ID
        self._init_ui()

    def _init_ui(self):
        self.pack(fill='both', expand=True)
        self.grid_columnconfigure(0, weight=0)
        self.grid_columnconfigure(1, weight=1)

        lab_padx, lab_pady = 12, 8

        appid_lab = ctk.CTkLabel(self, text='AppID:')
        appid_lab.grid(row=0, column=0, sticky='e', padx=lab_padx, pady=lab_pady)
        self.appIdEdit = ctk.CTkEntry(self, placeholder_text='请输入AppID', width=480)
        self.appIdEdit.insert(0, self._env.get('AppID', ''))
        self.appIdEdit.grid(row=0, column=1, sticky='we', padx=lab_padx, pady=lab_pady)

        appsec_lab = ctk.CTkLabel(self, text='AppSecret:')
        appsec_lab.grid(row=1, column=0, sticky='e', padx=lab_padx, pady=lab_pady)
        self.appSecretEdit = ctk.CTkEntry(self, placeholder_text='请输入AppSecret', show='*', width=480)
        self.appSecretEdit.insert(0, self._env.get('AppSecret', ''))
        self.appSecretEdit.grid(row=1, column=1, sticky='we', padx=lab_padx, pady=lab_pady)

        env_lab = ctk.CTkLabel(self, text='环境模式:')
        env_lab.grid(row=2, column=0, sticky='e', padx=lab_padx, pady=lab_pady)
        env_row = ctk.CTkFrame(self)
        env_row.grid(row=2, column=1, sticky='w', padx=lab_padx, pady=lab_pady)
        self.debugSwitch = ctk.CTkSwitch(env_row, text='')
        (self.debugSwitch.select() if (self._env.get('DEBUG', 'true') == 'true') else self.debugSwitch.deselect())
        self.envStateLabel = ctk.CTkLabel(env_row, text='开发' if self._env.get('DEBUG', 'true') == 'true' else '生产')
        def on_switch():
            self.envStateLabel.configure(text='开发' if self.debugSwitch.get() else '生产')
        self.debugSwitch.configure(command=on_switch)
        self.debugSwitch.pack(side='left', padx=8)
        self.envStateLabel.pack(side='left', padx=8)

        markup_lab = ctk.CTkLabel(self, text='上浮规则:')
        markup_lab.grid(row=3, column=0, sticky='e', padx=lab_padx, pady=lab_pady)
        markupRow = ctk.CTkFrame(self)
        markupRow.grid(row=3, column=1, sticky='we', padx=lab_padx, pady=lab_pady)
        self.markup_type_var = ctk.StringVar(value=self._env.get('PRICE_MARKUP_TYPE', '固定上浮') if self._env.get('PRICE_MARKUP_TYPE', '固定上浮') in ['固定上浮', '比例上浮'] else '固定上浮')
        self.markupTypeCombo = ctk.CTkOptionMenu(markupRow, variable=self.markup_type_var, values=['固定上浮', '比例上浮'])
        self.markupTypeCombo.pack(side='left', padx=8)
        self.markupValueEdit = ctk.CTkEntry(markupRow, width=120)
        self.markupValueEdit.insert(0, str(self._env.get('PRICE_MARKUP_VALUE', '0')))
        self.markupValueEdit.pack(side='left', padx=8)
        self.markupUnitLabel = ctk.CTkLabel(markupRow, text='元' if self.markup_type_var.get() == '固定上浮' else '%')
        def on_type_change(choice):
            self.markupUnitLabel.configure(text='元' if choice == '固定上浮' else '%')
        self.markupTypeCombo.configure(command=on_type_change)
        self.markupUnitLabel.pack(side='left', padx=8)

        cookie_lab = ctk.CTkLabel(self, text='COOKIE:')
        cookie_lab.grid(row=4, column=0, sticky='ne', padx=lab_padx, pady=lab_pady)
        self.cookieEdit = ctk.CTkTextbox(self, height=140)
        self.cookieEdit.insert('1.0', self._env.get('COOKIE', ''))
        self.cookieEdit.grid(row=4, column=1, sticky='nsew', padx=lab_padx, pady=lab_pady)

        btnRow = ctk.CTkFrame(self)
        btnRow.grid(row=5, column=1, sticky='w', padx=lab_padx, pady=(lab_pady, lab_pady))
        # 自动获取Cookie按钮
        self.autoCookieBtn = ctk.CTkButton(btnRow, text='自动获取Cookie', command=self._on_auto_cookie_click)
        self.saveBtn = ctk.CTkButton(btnRow, text='保存配置', command=self._emit_save)
        self.connectBtn = ctk.CTkButton(btnRow, text='连接服务', command=self._emit_connect)
        self.statusLabel = ctk.CTkLabel(self, text='状态: 未连接')
        self.autoCookieBtn.pack(side='left', padx=8)
        self.saveBtn.pack(side='left', padx=8)
        self.connectBtn.pack(side='left', padx=8)
        self.statusLabel.grid(row=6, column=1, sticky='w', padx=lab_padx, pady=(0, 12))

    def _emit_save(self):
        data = self.collect_data()
        if callable(self.on_save):
            self.on_save(data)

    def _emit_connect(self):
        cookie = self.cookieEdit.get('1.0', 'end').strip()
        if callable(self.on_connect):
            self.on_connect(cookie)

    def collect_data(self) -> dict:
        return {
            'AppID': self.appIdEdit.get().strip(),
            'AppSecret': self.appSecretEdit.get().strip(),
            'DEBUG': str(bool(self.debugSwitch.get())).lower(),
            'COOKIE': self.cookieEdit.get('1.0', 'end').strip(),
            'PRICE_MARKUP_TYPE': self.markup_type_var.get().strip(),
            'PRICE_MARKUP_VALUE': self.markupValueEdit.get().strip() or '0'
        }

    def set_connecting(self):
        self.connectBtn.configure(state='disabled', text='连接中...')
        self.statusLabel.configure(text='状态: 连接中...')

    def set_connected(self):
        self.connectBtn.configure(state='normal', text='断开连接')
        self.statusLabel.configure(text='状态: 已连接')

    def set_disconnected(self, reason: str = ''):
        self.connectBtn.configure(state='normal', text='连接服务')
        self.statusLabel.configure(text='状态: ' + (reason or '未连接'))

    # ========== 自动获取Cookie相关方法 ==========
    def _on_auto_cookie_click(self):
        """
        处理自动获取Cookie按钮点击事件
        """
        # 如果正在倒计时，忽略点击
        if self._countdown_value > 0:
            return
        
        # 如果按钮文字是"立即获取"，则执行获取Cookie操作
        if self.autoCookieBtn.cget('text') == '立即获取':
            self._fetch_cookie()
            return
        
        # 否则启动浏览器并开始倒计时
        self._start_browser_and_countdown()
    
    def _start_browser_and_countdown(self):
        """
        启动浏览器并开始倒计时
        """
        if self._cookie_fetcher and self._cookie_fetcher.is_browser_open():
            self.autoCookieBtn.configure(state='disabled', text='正在打开浏览器...')
            self.after(0, self._start_countdown)
            return
        # 在后台线程中启动浏览器
        def open_browser():
            try:
                # 延迟导入，避免启动时检查依赖
                from utils.cookie_fetcher import BrowserCookieFetcher
                
                # 创建Cookie获取器实例
                self._cookie_fetcher = BrowserCookieFetcher()
                
                # 打开浏览器
                if self._cookie_fetcher.open_browser_for_login():
                    # 浏览器打开成功，在主线程中开始倒计时
                    self.after(0, self._start_countdown)
                else:
                    self.after(0, lambda: self._reset_button_state('浏览器启动失败', True))
            except ImportError:
                # selenium未安装
                self.after(0, lambda: self._show_install_selenium_error())
            except Exception as e:
                self.after(0, lambda: self._reset_button_state(f'错误: {str(e)}', True))
        
        # 设置按钮为禁用状态
        self.autoCookieBtn.configure(state='disabled', text='正在打开浏览器...')
        
        # 启动后台线程
        threading.Thread(target=open_browser, daemon=True).start()
    
    def _start_countdown(self):
        """
        开始8秒倒计时
        """
        self._countdown_value = 8
        self._update_countdown()
    
    def _update_countdown(self):
        """
        更新倒计时显示
        """
        if self._countdown_value > 0:
            # 更新按钮文字
            self.autoCookieBtn.configure(
                state='disabled',
                text=f'正在打开浏览器 ({self._countdown_value}秒)'
            )
            # 倒计时减1
            self._countdown_value -= 1
            # 1秒后继续更新
            self._countdown_after_id = self.after(1000, self._update_countdown)
        else:
            # 倒计时结束，设置按钮为"立即获取"
            self.autoCookieBtn.configure(
                state='normal',
                text='立即获取'
            )
            self._countdown_after_id = None
    
    def _fetch_cookie(self):
        """
        从浏览器获取Cookie并填充到输入框
        """
        # 设置按钮为禁用状态
        self.autoCookieBtn.configure(state='disabled', text='正在获取...')
        
        # 在后台线程中获取Cookie
        def get_cookie():
            try:
                if self._cookie_fetcher and self._cookie_fetcher.is_browser_open():
                    # 获取Cookie
                    cookie_str = self._cookie_fetcher.get_cookies()
                    
                    if cookie_str:
                        # 获取成功，更新UI
                        self.after(0, lambda: self._update_cookie_field(cookie_str))
                    else:
                        # 获取失败
                        self.after(0, lambda: self._reset_button_state('获取Cookie失败'))
                else:
                    self.after(0, lambda: self._reset_button_state('浏览器已关闭'))
            except Exception as e:
                self.after(0, lambda: self._reset_button_state(f'错误: {str(e)}', True))
        
        # 启动后台线程
        threading.Thread(target=get_cookie, daemon=True).start()
    
    def _update_cookie_field(self, cookie_str: str):
        """
        更新Cookie输入框内容
        
        参数:
            cookie_str: Cookie字符串
        """
        self.cookieEdit.delete('1.0', 'end')
        self.cookieEdit.insert('1.0', cookie_str)
        self._countdown_value = 0
        self.autoCookieBtn.configure(state='normal', text='立即获取')
        messagebox.showinfo('成功', 'Cookie获取成功！', parent=self.winfo_toplevel())
    
    def _reset_button_state(self, error_msg: str = None, close_browser: bool = False):
        """
        重置按钮状态为初始状态
        
        参数:
            error_msg: 错误消息，如果不为None则显示错误对话框
        """
        # 取消倒计时（如果有）
        if self._countdown_after_id is not None:
            try:
                self.after_cancel(self._countdown_after_id)
            except Exception:
                pass
            self._countdown_after_id = None
        
        # 重置倒计时值
        self._countdown_value = 0
        
        if close_browser and self._cookie_fetcher:
            self._cookie_fetcher.close_browser()
            self._cookie_fetcher = None
        
        # 恢复按钮状态
        self.autoCookieBtn.configure(state='normal', text='自动获取Cookie')
        
        # 显示错误消息（如果有）
        if error_msg:
            messagebox.showerror('错误', error_msg, parent=self.winfo_toplevel())

    def shutdown(self):
        try:
            if self._countdown_after_id is not None:
                try:
                    self.after_cancel(self._countdown_after_id)
                except Exception:
                    pass
                self._countdown_after_id = None
            self._countdown_value = 0
            if self._cookie_fetcher:
                try:
                    self._cookie_fetcher.close_browser()
                except Exception:
                    pass
                self._cookie_fetcher = None
        except Exception:
            pass
    
    def _show_install_selenium_error(self):
        """
        显示selenium未安装的错误提示
        """
        error_msg = (
            "selenium库未安装，无法使用自动获取Cookie功能。\n\n"
            "请在命令行中运行以下命令安装依赖：\n"
            "pip install selenium webdriver-manager"
        )
        self._reset_button_state(error_msg, True)

